package ca.camosun.morsecode;

import java.util.Timer;
import java.util.TimerTask;

import ca.camosun.morsecode.nongui.MorseQueue;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.EditText;
import static ca.camosun.morsecode.nongui.MorseConstants.Token.*;

public class ManualMorse extends Activity {

	private int timePressed;
	private int timeReleased;
	
	private Timer tapTimer;
	
	private MorseQueue toDecode;
	private EditText readableMessage;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.manual_morse);

		timePressed = 0;
		timeReleased = 0;

		tapTimer = new Timer();
		toDecode = new MorseQueue();

		readableMessage = (EditText) findViewById(R.id.decoded_text);
	}

	@Override
	public boolean onTouchEvent(MotionEvent touch) {

		TimerTask pressedTimer = new IncrementPressedTimer();
		TimerTask ReleasedTimer = new IncrementReleassedTimmer();

		switch (touch.getAction()) {
		case MotionEvent.ACTION_DOWN:

			// Since the screen has been /pressed/ right now...
			if (timeReleased <= SHORT_PAUSE.getRelativeTime()) {

				toDecode.addToken(SHORT_PAUSE);

			}

			if (timeReleased > SHORT_PAUSE.getRelativeTime()) {

				if (timeReleased <= LONG_PAUSE.getRelativeTime()) {

					toDecode.addToken(LONG_PAUSE);
					outputMessage();

				}
			}

			timeReleased = 0;
			tapTimer.scheduleAtFixedRate(pressedTimer, 0, 100);

		case MotionEvent.ACTION_UP:

			// The screen has been /released/, what do we do?
			if (timePressed <= DOT.getRelativeTime()) {
				toDecode.addToken(DOT);
			}

			if (timePressed <= DASH.getRelativeTime()) {

				if (timePressed > DOT.getRelativeTime()) {

					toDecode.addToken(DASH);
				}
			}

			timePressed = 0;
			tapTimer.scheduleAtFixedRate(ReleasedTimer, 0, 100);
		}
		return true;
	}

	void outputMessage() {

		String decoded = "";
		while (toDecode.hasNext()) {
			decoded += toDecode.getNextDecoded();
		}
		
		readableMessage.append(decoded);
	}

	class IncrementPressedTimer extends TimerTask {

		@Override
		public void run() {
			timePressed += 100;
		}
	}

	class IncrementReleassedTimmer extends TimerTask {

		@Override
		public void run() {
			timeReleased += 100;
		}
	}
}
